from django.http import QueryDict
from django.template import Library
from django.conf import settings
from django.urls import reverse
from django.utils.safestring import mark_safe

register = Library()


def have_permission(request, name):
    # 判断当前登录的用户是否
    role = request.wl_user.role
    permission_dict = settings.WL_PERMISSION[role]

    if name in permission_dict:
        return True


@register.simple_tag
def add_permission(request, name, *args, **kwargs):
    if not have_permission(request, name):
        return ""

    url = reverse(name, args=args, kwargs=kwargs)

    html_string = f"""
    <a href="{url}" class="btn btn-success">
            <span class="glyphicon glyphicon-plus-sign"></span> 新建
        </a>
    """
    return mark_safe(html_string)


@register.simple_tag
def edit_permission(request, name, *args, **kwargs):
    if not have_permission(request, name):
        return ""

    url = reverse(name, args=args, kwargs=kwargs)

    # 取到的查询参数 keyword=A&page=9
    param = request.GET.urlencode()
    new_query_dict = QueryDict(mutable=True)
    new_query_dict['_filter'] = param

    # 如果没有查询字符串 就不拼接 _filter
    if not param:
        html_string = f"""
            <a href="{url}" class="btn btn-primary btn-xs">编辑</a>
            """
        return mark_safe(html_string)

    filter_string = new_query_dict.urlencode()   #  _filter=keyword%3DA%26page%3D9
    html_string = f"""
    <a href="{url}?{filter_string}" class="btn btn-primary btn-xs">编辑</a>
    """
    return mark_safe(html_string)


@register.simple_tag
def delete_permission(request, name, *args, **kwargs):
    if not have_permission(request, name):
        return ""

    pk = kwargs.get("pk")

    html_string = f"""
    <a cid={pk} href="" class="btn btn-danger btn-xs btn-delete">删除</a>
    """
    return mark_safe(html_string)


@register.simple_tag
def delete_url_permission(request, name, *args, **kwargs):
    if not have_permission(request, name):
        return ""

    url = reverse(name, args=args, kwargs=kwargs)

    html_string = f"""
    <a href="{url}" class="btn btn-danger btn-xs">删除</a>
    """
    return mark_safe(html_string)


@register.filter
def check_permission(request, others):
    name_list = others.split(',')
    for name in name_list:
        status = have_permission(request, name)
        # 只要有一个在权限列表中，都会输出 True 进行展示
        if status:
            return True
    # 全部都没有权限，才不展示 输出 False
    return False
